package sixyz.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 默认拦截所有访问
@WebFilter("/*")
public class IllegalAccessInterception implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 得到uri
        String uri = request.getRequestURI();
        // 放行访问登录页面的请求
        if (uri.contains("login.jsp") || uri.contains("register.jsp")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 放行静态资源
        if (uri.contains("/css") || uri.contains("/images")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 放行登录和操作
        if (uri.contains("login") || uri.contains("/register")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 用户已登录，放行
        if (request.getSession().getAttribute("user") != null) {
            filterChain.doFilter(request, response);
            return;
        }
        // 其余访问通通拦截至login.jsp
        response.sendRedirect("login.jsp");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
